﻿#include "AccountBookAdd.h"
#include "ui_AccountBookAdd.h"
#include "AccountBookDBManage.h"

AccountBookAdd::AccountBookAdd(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AccountBookAdd)
{
    ui->setupUi(this);
    initStyle();

    connect(ui->pushButton_in, SIGNAL(clicked()), this, SLOT(slotUpdateStyleComBox()));
    connect(ui->pushButton_out, SIGNAL(clicked()), this, SLOT(slotUpdateStyleComBox()));
    ui->pushButton_out->click();

    // 金额限制只能输入数字和小数点
    QRegExp regx("[0-9.0-9]*");
    QValidator *validator = new QRegExpValidator(regx, ui->lineEdit_num);
    ui->lineEdit_num->setValidator(validator);
}

AccountBookAdd::~AccountBookAdd()
{
    delete ui;
}

void AccountBookAdd::slotAccountAdd()
{
    if(ui->lineEdit_num->text().isEmpty())
        return;

    AccountItem accountItem;
    accountItem.type = ui->comboBox_style->currentText();
    accountItem.inOrOut = ui->pushButton_in->isChecked() ? 1 : 0;
    accountItem.amount = ui->lineEdit_num->text().toDouble();
    accountItem.time = ui->dateEdit_time->date();
    accountItem.note = ui->lineEdit_note->text();
    accountItem.currentTime = QDateTime::currentDateTime();

    // TODO 数据库账单表格增加一条数据
    bool isAdd = AccountBookDBManage::getInstance()->addAccountItem(accountItem);
    if(isAdd)
        emit sigAddSuccessed();
}

void AccountBookAdd::slotUpdateStyleComBox()
{
    QPushButton *btn = qobject_cast<QPushButton *>(sender());
    if(btn == ui->pushButton_out)
        updateStyleCombox(m_styleOut);
    else if(btn == ui->pushButton_in)
        updateStyleCombox(m_styleIn);
}

void AccountBookAdd::initStyle()
{
    m_styleIn = AccountBookDBManage::getInstance()->searchStyleByInOrOut(1);
    m_styleOut = AccountBookDBManage::getInstance()->searchStyleByInOrOut(0);
}

void AccountBookAdd::updateStyleCombox(QStringList lst)
{
    ui->comboBox_style->clear();
    ui->comboBox_style->addItems(lst);
}
